package cn.itcast.weatherapp123.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtil {

    public static final String URL_WEATHER_WITH_FUTURE="https://yiketianqi.com/api?unescape=1&version=v1&appid=84254468&appsecret=F1VYQPFH ";

    public static String doGet(String urlStr)  {

        String result="";
        HttpURLConnection httpURLConnection=null;
        InputStreamReader inputStreamReader=null;
        BufferedReader bufferedReader=null;

        //连接网络
        try {
            URL url=new URL(urlStr);
            httpURLConnection= (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("GET");

            httpURLConnection.setConnectTimeout(5000);

            //从连接中读取数据(二进制)
            InputStream inputStream=httpURLConnection.getInputStream();

            inputStreamReader=new InputStreamReader(inputStream);

            //二进制流送入缓冲区
            bufferedReader=new BufferedReader(inputStreamReader);

            //从缓冲区中一行行读取字符串
            StringBuilder stringBuilder=new StringBuilder();

            String line="";

            while ((line=bufferedReader.readLine())!=null){
                stringBuilder.append(line);
            }

            result=stringBuilder.toString();

        } catch (Exception e) {
            e.printStackTrace();

        }finally {
            if (httpURLConnection!=null){

                httpURLConnection.disconnect();

            }

            if (inputStreamReader!=null){

                try {

                    inputStreamReader.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (bufferedReader!=null){

                    try {

                        bufferedReader.close();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
        return  result;
    }

    public static String getweatherOfCity(String city){

        String result="";

        //并接出获取天气数据的URL
        //https://yiketianqi.com/api?unescape=1&version=v1&appid=84254468&appsecret=F1VYQPFH&city=汕头市
        String weatherUrl=URL_WEATHER_WITH_FUTURE+"&city="+city;
        Log.e("fan","----------weatherUrl-----------"+weatherUrl);

        String weatherResult=doGet(weatherUrl);
        Log.e("tag","----------weatherResult-----------"+weatherResult);
        return weatherResult;
    }

}
